class Solution:
    def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
        str_n = str(n)
        Ld, Ln, a, sum = len(digits), len(str_n), 1, 0

        

        if Ln == 1:
            for i in digits:
                if i <= str_n:
                    sum += 1
            return sum
        
        for i in range(Ln - 1):
            a *= Ld
            sum += a

        m, list_n, c, L = 0, list(str_n), True, 1
        for i in list_n:
            for j in digits:
                if j < i:
                    m += 1
                elif j == i:
                    if L == Ln:
                        sum += m + 1
                        return int(sum)
                    c = False
            L += 1
            sum += m * a
            if c:
                break
            a /= Ld
            m = 0
            c = True

        return int(sum)